from bokeh.plotting import figure
import json
import pandas as pd
import numpy as np
from bokeh.models import FactorRange
from bokeh.transform import factor_cmap
from bokeh.models import ColumnDataSource
from bokeh.palettes import Spectral5

def sum_values(p):
    with open('static/data/高校信息.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    data_mul = [[i['province_name'], len(j['universities'])] for i in data['schools'] for j in i['cities']]
    data_mul
    total = 0
    for ele in range(0, len([j[1] for i, j in enumerate(data_mul) if j[0] == p])):
        total = total + [j[1] for i, j in enumerate(data_mul) if j[0] == p][ele]
    return (total)


def uni():
    school = pd.read_csv('static/data/学校数量.csv')
    year = np.array(school.loc[[1]]).tolist()[0]
    del year[0]
    university = np.array(school.loc[[2]]).tolist()[0]
    del university[0]
    universities = [int(x) for x in university]

    years = year
    universities = universities

    source = ColumnDataSource(
        data=dict(
            x=years,
            universities=universities
        )
    )

    TOOLTIPS = [
        ("count", "@universities")
    ]

    p = figure(
        x_range=years,
        plot_height=350,
        title="普通高校数量",
        tooltips=TOOLTIPS
    )
    p.vbar(x="x", top="universities", width=0.8, source=source, color="#66CC33")

    p.xgrid.grid_line_color = None
    p.y_range.start = 0

    return p

def high():
    school = pd.read_csv('static/data/学校数量.csv')
    year = np.array(school.loc[[1]]).tolist()[0]
    del year[0]
    highschool = np.array(school.loc[[3]]).tolist()[0]
    del highschool[0]
    highschool = [int(x) for x in highschool]

    years = year
    highschool = highschool

    source = ColumnDataSource(
        data=dict(
            x=years,
            highschool=highschool
        )
    )

    TOOLTIPS = [
        ("count", "@highschool")
    ]

    p = figure(
        x_range=years,
        plot_height=350,
        title="普通高中数量",
        tooltips=TOOLTIPS
    )
    p.vbar(x="x", top="highschool", width=0.8, source=source, color="#669999")

    p.xgrid.grid_line_color = None
    p.y_range.start = 0

    return p

def middle():
    school = pd.read_csv('static/data/学校数量.csv')
    year = np.array(school.loc[[1]]).tolist()[0]
    del year[0]
    middleschool = np.array(school.loc[[4]]).tolist()[0]
    del middleschool[0]
    middleschool = [int(x) for x in middleschool]

    years = year
    middleschool = middleschool

    source = ColumnDataSource(
        data=dict(
            x=years,
            middleschool=middleschool
        )
    )

    TOOLTIPS = [
        ("count", "@middleschool")
    ]

    p = figure(
        x_range=years,
        plot_height=350,
        title="初中学校数量",
        tooltips=TOOLTIPS
    )
    p.vbar(x="x", top="middleschool", width=0.8, source=source, color="#CC6666")

    p.xgrid.grid_line_color = None
    p.y_range.start = 0

    return p

def others():
    school = pd.read_csv('static/data/学校数量.csv')
    year = np.array(school.loc[[1]]).tolist()[0]
    del year[0]
    schools = school['数据库：年度数据'].tolist()
    del schools[0:5]
    del schools[3]
    x = [(year, school) for year in year for school in schools]
    #小学
    primary = np.array(school.loc[[5]]).tolist()[0]
    del primary[0]
    primary = [int(x) for x in primary]
    #特殊教育学校
    special = np.array(school.loc[[6]]).tolist()[0]
    del special[0]
    special = [int(x) for x in special]
    #学前教育学校
    pre = np.array(school.loc[[7]]).tolist()[0]
    del pre[0]
    pre = [int(x) for x in pre]
    counts = sum(zip(primary, special, pre), ())

    source = ColumnDataSource(data=dict(x=x, counts=counts))

    palette = ["#c9d9d3", "#718dbf", "#e84d60"]
    TOOLTIPS = [
        ("count", "@counts")
    ]

    p = figure(x_range=FactorRange(*x), plot_height=800, plot_width=1000, title="2012-2021年间普通小学、特殊学校、学前教育学校数量变化",
               tooltips=TOOLTIPS)

    p.vbar(x='x', top='counts', width=1, source=source, line_color="white",
           fill_color=factor_cmap('x', palette=palette, factors=schools, start=1, end=2))

    p.y_range.start = 0
    p.x_range.range_padding = 0.1
    p.xaxis.major_label_orientation = 1
    p.xgrid.grid_line_color = None

    return p

def student():
    student = pd.read_csv('static/data/招生数量.csv')
    time = np.array(student.loc[[1]]).tolist()[0]
    del time[0]
    del time[3:-1]
    del time[-1]

    schools = student['数据库：年度数据'].tolist()
    del schools[0:2]
    del schools[-3:-1]
    del schools[-1]
    #高校
    university = np.array(student.loc[[2]]).tolist()[0]
    del university[0]
    del university[3:-1]
    del university[-1]
    university = [float(x) for x in university]
    universities = [int(x) for x in university]
    #高中
    high = np.array(student.loc[[3]]).tolist()[0]
    del high[0]
    del high[3:-1]
    del high[-1]
    high = [float(x) for x in high]
    highschools = [int(x) for x in high]
    #初中
    middle = np.array(student.loc[[4]]).tolist()[0]
    del middle[0]
    del middle[3:-1]
    del middle[-1]
    middle = [float(x) for x in middle]
    middleschools = [int(x) for x in middle]

    schools = schools
    years = time
    colors = ["#c9d9d3", "#718dbf", "#e84d60"]

    data = {'schools': schools,
            '2021年': [university[0], highschools[0], middleschools[0]],
            '2020年': [university[1], highschools[1], middleschools[1]],
            '2019年': [university[2], highschools[2], middleschools[2]]}

    p = figure(x_range=schools, height=250, title="2019-2021年间普通高校、普通高中以及初中招生人数",
               toolbar_location=None, tools="hover", tooltips="$name @schools: @$name")

    p.vbar_stack(years, x='schools', width=0.9, color=colors, source=data,
                 legend_label=years)

    p.y_range.start = 0
    p.x_range.range_padding = 0.1
    p.xgrid.grid_line_color = None
    p.axis.minor_tick_line_color = None
    p.outline_line_color = None
    p.legend.location = "top_left"
    p.legend.orientation = "horizontal"

    return p

def in_student():
    student = pd.read_csv('static/data/招生数量.csv')
    student_inschool = pd.read_csv('static/data/在校生.csv')
    #时间
    time = np.array(student.loc[[1]]).tolist()[0]
    del time[0]
    del time[3:-1]
    del time[-1]
    #x轴
    studying = student_inschool['数据库：年度数据'].tolist()
    del studying[0:2]
    del studying[1]
    del studying[3:-1]
    del studying[-1]

    #高校
    in_university = np.array(student_inschool.loc[[2]]).tolist()[0]
    del in_university[0]
    del in_university[3:-1]
    del in_university[-1]
    in_university = [float(x) for x in in_university]
    in_university = [int(x) for x in in_university]
    #高中
    in_highschool = np.array(student_inschool.loc[[4]]).tolist()[0]
    del in_highschool[0]
    del in_highschool[3:-1]
    del in_highschool[-1]
    in_highschool = [float(x) for x in in_highschool]
    in_highschool = [int(x) for x in in_highschool]
    #初中
    in_middleschools = np.array(student_inschool.loc[[5]]).tolist()[0]
    del in_middleschools[0]
    del in_middleschools[3:-1]
    del in_middleschools[-1]
    in_middleschools = [float(x) for x in in_middleschools]
    in_middleschools = [int(x) for x in in_middleschools]


    schools = studying
    years = time
    colors = ["#c9d9d3", "#718dbf", "#e84d60"]

    data = {'schools': studying,
            '2021年': [in_university[0], in_highschool[0], in_middleschools[0]],
            '2020年': [in_university[1], in_highschool[1], in_middleschools[1]],
            '2019年': [in_university[2], in_highschool[2], in_middleschools[2]]}

    p = figure(x_range=schools, height=250, title="2019-2021年间普通高校、普通高中以及初中在校人数",
               toolbar_location=None, tools="hover", tooltips="$name @schools: @$name")

    p.vbar_stack(years, x='schools', width=0.9, color=colors, source=data,
                 legend_label=years)

    p.y_range.start = 0
    p.x_range.range_padding = 0.1
    p.xgrid.grid_line_color = None
    p.axis.minor_tick_line_color = None
    p.outline_line_color = None
    p.legend.location = "top_left"
    p.legend.orientation = "horizontal"

    return p

def teachers():
    teacher = pd.read_csv('static/data/教师数量.csv')
    #高校
    uni_teacher = np.array(teacher.loc[[2]]).tolist()[0]
    del uni_teacher[0]
    del uni_teacher[3:-1]
    del uni_teacher[-1]
    uni_teacher = [float(x) for x in uni_teacher]
    #高中
    high_teacher = np.array(teacher.loc[[3]]).tolist()[0]
    del high_teacher[0]
    del high_teacher[3:-1]
    del high_teacher[-1]
    high_teacher = [float(x) for x in high_teacher]
    #初中
    middle_teacher = np.array(teacher.loc[[4]]).tolist()[0]
    del middle_teacher[0]
    del middle_teacher[3:-1]
    del middle_teacher[-1]
    middle_teacher = [float(x) for x in middle_teacher]
    #小学
    primary_teacher = np.array(teacher.loc[[5]]).tolist()[0]
    del primary_teacher[0]
    del primary_teacher[3:-1]
    del primary_teacher[-1]
    primary_teacher = [float(x) for x in primary_teacher]

    source = ColumnDataSource(
        data=dict(
            years=['2021', '2020', '2019'],
            uni=uni_teacher,
            high=high_teacher,
            middle=middle_teacher,
            primary=primary_teacher
        )
    )

    p = figure(
        plot_height=500,
        plot_width=800,
        tools="pan,box_zoom,reset,save",
        title="2019-2021年学校专任教师数量",
        x_axis_label="年份",
        y_axis_label="数量（万人）",
        tooltips=[('count', '@$name')]
    )

    p.line(x='years', y='uni', legend="普通高校", name='uni', source=source)
    p.circle(x='years', y='uni', legend="普通高校", fill_color="white", size=8, name='uni', source=source)

    p.line(x='years', y='high', legend="普通高中", line_color="green", source=source)
    p.circle(x='years', y='high', legend="普通高中", fill_color="white", size=8, name="high", source=source)

    p.line(x='years', y='middle', legend="初中", line_color="yellow", source=source)
    p.circle(x='years', y='middle', legend="初中", fill_color="white", size=8, name="middle", source=source)

    p.line(x='years', y='primary', legend="普通小学", line_color="pink", source=source)
    p.circle(x='years', y='primary', legend="普通小学", fill_color="white", size=8, name="primary", source=source)

    # 图例设置
    p.legend.location = (1, 250)
    p.legend.click_policy = "hide"

    return p

def percent():
    proportion = pd.read_csv('static/data/师生比.csv')
    year_2020 = proportion['Unnamed: 2'].tolist()
    del year_2020[0:2]
    del year_2020[-1]
    year_2020 = [float(x) for x in year_2020]

    data_name = proportion['数据库：年度数据'].tolist()
    del data_name[0:2]
    del data_name[-1]

    data_name = data_name
    year_2020 = year_2020

    source = ColumnDataSource(
        data=dict(
            data_name=data_name,
            year_2020=year_2020,
            color=Spectral5
        )
    )

    TOOLTIPS = [
        ("师生比", "@year_2020")
    ]

    p = figure(
        x_range=data_name,
        plot_height=600,
        plot_width=800,
        title="2020年各类学校师生比例情况（教师人数=1）",
        tooltips=TOOLTIPS
    )
    p.vbar(x="data_name", top="year_2020", width=0.8, color='color', legend='data_name', source=source)

    p.xgrid.grid_line_color = None
    p.y_range.start = 0
    p.legend.location = 'top_center'

    return p

def fund():
    p = figure(plot_width=800, plot_height=500, title='历年教育经费', tooltips=[('教育经费', '@$name')])
    edu_fund = pd.read_csv('static/data/edu经费.csv')
    year = [2020, 2019, 2018, 2017, 2016, 2015, 2014, 2013, 2012]
    fund = np.array(edu_fund.loc[[2]]).tolist()[0]
    del fund[0:2]
    fund = [int(x) for x in fund]

    source = ColumnDataSource(
        data=dict(
            years=year,
            funds=fund,
        )
    )
    p.xaxis.axis_label = '年份'
    p.yaxis.axis_label = '教育经费（元）'



    p.line('years', 'funds', color="navy", line_width=2, source=source, name='funds', legend_label='教育经费')

    p.legend.location = 'top_left'

    return p

def sum_values(p):
    with open('static/data/高校信息.json', 'r', encoding='utf-8') as f:
        data = json.load(f)
    data_mul = [[i['province_name'], len(j['universities'])] for i in data['schools'] for j in i['cities']]

    total = 0
    for ele in range(0, len([j[1] for i,j in enumerate(data_mul) if j[0]==p])):
        total = total + [j[1] for i,j in enumerate(data_mul) if j[0]==p][ele]
    return(total)